#include<PubSubClient.h>
#include<WiFi.h>
// 创建mqtt连接对象
extern WiFiClient esp32Client;
extern PubSubClient client(esp32Client);

// mqtt config
extern const char *mqtt_broker;               // 卡夫卡服务器
extern const char *sub_topic1;       // 订阅的接受消息的频道
extern const char *pub_topic;       // esp32 发送消息的频道
extern const char *mqtt_clientname;          
extern const char *mqtt_password;
extern const int mqtt_port;


extern int16_t hei = 35;                           // 变化的高

// 回调函数，若接收到subscribe的主题的信息：
extern void callback_mess(char *topic, byte *payload, unsigned int length) {
  // 后续放到屏幕中
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");

  if(!strcmp(topic, sub_topic1)){
    // 解析负载字节数组为字符串
    char* str = (char*) malloc(length + 1); // 加上 '\0'
    memset(str, 0, length + 1); // 初始化为 0
    memcpy(str, payload, length);
    Serial.printf("%s\n", str);

    tft.setTextDatum(CC_DATUM);   
    if(hei < 355){
      //tft.drawString(("Get message"), 40, hei, 2);
      _xFont->DrawChinese(40, hei, str, TFT_GREEN);
      Serial.println(hei);
      hei += 80;
    }
    free(str); // 释放内存
    Serial.println();
    Serial.println("-----------------------");
  }
  // else if(!strcmp(topic, sub_topic2)){}
}

extern void connect_mqtt_server() {
  while(!client.connected()) {
  String client_id = "esp32-client-";
  client_id == String(WiFi.macAddress());           // client_id 可以设置复杂一些
  Serial.printf("connecting to mqtt broker\n");
  if (client.connect(client_id.c_str(), mqtt_clientname, mqtt_password)) {           // esp32重新与broker建立连接
      Serial.println("Public emqx mqtt broker connected");
    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
}


